package com.condroid;

/**
 * This class used to parse the command
 * received from users to executable 
 * command of the application.
 * This class normal only need to be
 * invoked by CmdCmit class.
 * @author JUN GAO
 * Condroid Summer CSD 2011 - KTH
 */
public class CmdParser {
	private String cmdOriginal;
	private String[] cmd;
	private int type;
	private int shtcutIndex;
	
	public CmdParser(){}
	
	/**
	 * @param cmdOriginal The command provided by user
	 */
	public void setCmd(String cmdOriginal){
		this.cmdOriginal = cmdOriginal.trim();
		
		if(this.cmdOriginal.startsWith("*"))
			type = ConstantData.SHTCUTCMD;
		else if(this.cmdOriginal.startsWith("$"))
			type = ConstantData.INNEREXECMD;
		else
			type = ConstantData.OUTERCMD;
	}
	
	/**
	 * After use {@link #setCmd(String)} method provided command,
	 * need to use this method to check the correction
	 * of the command.
	 * @return if command is OK return true or return
	 * false
	 */
	public boolean checkCmd(){
		//TODO command check
		switch(type){
		case ConstantData.SHTCUTCMD:
			return checkShtcutCmd();
		case ConstantData.INNEREXECMD:
			return checkInnerExeCmd();
		default:
			//TODO default treatment
			break;
		}
		
		return true;
	}
	
	private boolean checkShtcutCmd() {
		String[] s = cmdOriginal.split("*");
		if (s[0] != null) {
			try {
				shtcutIndex = Integer.parseInt(s[0].trim());
				if (shtcutIndex < 0)
					return false;
			} catch (NumberFormatException e) {
				return false;
			}
		}
		return true;
	}
	
	private boolean checkInnerExeCmd(){
		//TODO inner command checking
		return true;
	}
	
	/**
	 * After provide the command and check the command,
	 * use this method to get executable command for
	 * the application.
	 * @return A string array of command serial. Normally
	 * there will be only one element in the array except
	 * when command is shortcut command.
	 */
	public String[] parseCmd(){
		switch(type){
		case ConstantData.SHTCUTCMD:
			//TODO shortcut command parsing
			ShtcutSetting.getConfiguration(ConstantData.appContext);
			cmd = ShtcutSetting.getShortcut(shtcutIndex);
			break;
		case ConstantData.INNEREXECMD:
			//TODO inner executing command parsing
			break;
		case ConstantData.OUTERCMD:
			cmd = new String[1];
			cmd[0] = cmdOriginal.trim();
			break;
		}
		return cmd;
	}
	
	
	/**
	 * Use this method to get the command type defined 
	 * in class ConstantData.
	 * @return the integer stand for the type of command
	 */
	public int cmdType(){
		return type;
	}
}
